<template>
  <div class="database-backup-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>数据还原</h3>
        </div>
      </template>

      <el-table :data="backupList" border v-loading="loading">
        <el-table-column type="expand">
          <template #default="scope">
            <el-table :data="scope.row.parts" border>
              <el-table-column prop="name" label="文件名称" />
              <el-table-column label="操作" width="150" align="center">
                <template #default="partScope">
                  <el-button size="small" @click="handleDownload(partScope.row)">
                    下载备份
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <el-table-column prop="time" label="备份时间" width="200">
          <template #default="scope">
            <strong>备份时间：{{ scope.row.time }}</strong>
            <span v-if="scope.row.timespan == lockTime" class="incomplete-warning">
              该备份不是完整备份，请删除重新备份
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="format" label="文件格式" align="center" width="100" />

        <el-table-column prop="separator" label="分隔符" align="center" width="100" />

        <el-table-column prop="size" label="文件总大小" align="center" width="120" />

        <el-table-column prop="partCount" label="分卷总数" align="center" width="100" />

        <el-table-column label="操作" width="220" align="center">
          <template #default="scope">
            <div v-if="scope.row.timespan == lockTime">
              <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              <el-dropdown>
                <el-button size="small">
                  更多
                  <el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleClear(scope.row)">
                      清除不完整的备份
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <div v-else>
              <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              <el-dropdown>
                <el-button size="small">
                  更多
                  <el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleRestore(scope.row)">数据还原</el-dropdown-item>
                    <el-dropdown-item @click="handleDelete(scope.row)">删除备份</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="backupList.length === 0" class="no-backup">暂无备份数据</div>
    </el-card>

    <!-- 还原进度对话框 -->
    <el-dialog
      v-model="restoreDialogVisible"
      title="还原进度"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="restore-progress">
        <p>数据还原中...</p>
        <el-progress :percentage="restoreProgress" :stroke-width="18" />
        <p>{{ restoreMessage }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    getBackupList as getBackupListApi,
    importBackup as importBackupApi,
    deleteBackup as deleteBackupApi,
  } from '@/api/home/database'
  import { ArrowDown } from '@element-plus/icons-vue'

  // 数据相关
  const backupList = ref<any[]>([])
  const loading = ref(false)
  const lockTime = ref(0)

  // 还原相关
  const restoreDialogVisible = ref(false)
  const restoreProgress = ref(0)
  const restoreMessage = ref('')

  // 获取备份列表
  const getBackupList = async () => {
    try {
      loading.value = true
      const response: any = await getBackupListApi()

      // 确保数据格式正确
      if (Array.isArray(response.data)) {
        backupList.value = response.data
        lockTime.value = response.lock_time || 0
      } else if (response.data && Array.isArray(response.data.list)) {
        // 兼容可能的数据结构，如果数据在list字段中
        backupList.value = response.data.list
        lockTime.value = response.lock_time || 0
      } else {
        console.warn('Backup list data format is incorrect:', response.data)
        backupList.value = []
        lockTime.value = 0
      }
    } catch (error: any) {
      console.error('Failed to fetch backup list:', error)
      ElMessage.error('获取备份列表失败: ' + (error.message || '未知错误'))
      backupList.value = []
      lockTime.value = 0
    } finally {
      loading.value = false
    }
  }

  // 处理还原
  const handleRestore = async (row: any) => {
    restoreDialogVisible.value = true
    restoreProgress.value = 0
    restoreMessage.value = ''

    try {
      if (restoreProgress.value === 0) {
        restoreProgress.value = 10
        restoreMessage.value = '正在连接数据库...'
      }

      if (restoreProgress.value === 10) {
        restoreProgress.value = 30
        restoreMessage.value = '正在还原数据库，请不要关闭！'
      }

      const response: any = await importBackupApi({ time: row.timespan })

      if (response.code === 0) {
        restoreProgress.value = 100
        restoreMessage.value = response.msg
        ElMessage.success(response.msg)
        window.onbeforeunload = function () {
          return null
        }

        // 还原成功后刷新列表
        await getBackupList()
      } else {
        ElMessage.error(response.data.msg || '还原失败')
      }
    } catch (error) {
      ElMessage.error('还原失败')
    }
  }

  // 处理删除
  const handleDelete = (row: any) => {
    ElMessageBox.confirm('确认要删除该备份吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      try {
        const response: any = await deleteBackupApi({ time: row.timespan })

        ElMessage.success(response.msg)
        if (response.code === 0) {
          setTimeout(() => {
            location.reload()
          }, 2000)
        }
      } catch (error) {
        ElMessage.error('删除操作失败')
      }
    })
  }

  // 处理清除
  const handleClear = (row: any) => {
    ElMessageBox.confirm('确认要清除该备份吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      try {
        const response: any = await deleteBackupApi({
          time: row.timespan,
          lock: 1,
        })

        ElMessage.success(response.msg)
        if (response.code === 0) {
          setTimeout(() => {
            location.reload()
          }, 2000)
        }
      } catch (error) {
        ElMessage.error('清除操作失败')
      }
    })
  }

  // 查看备份详情
  const handleView = (row: any) => {
    // 使用弹窗展示备份详情
    let partsInfo = ''
    if (row.parts && row.parts.length > 0) {
      partsInfo = '<ul>'
      row.parts.forEach((part: any) => {
        partsInfo += `<li>${part.name}</li>`
      })
      partsInfo += '</ul>'
    } else {
      partsInfo = '<p>无分卷信息</p>'
    }

    ElMessageBox.alert(
      `
    <p><strong>备份时间:</strong> ${row.time}</p>
    <p><strong>文件格式:</strong> ${row.format}</p>
    <p><strong>分隔符:</strong> ${row.separator}</p>
    <p><strong>文件总大小:</strong> ${row.size}</p>
    <p><strong>分卷总数:</strong> ${row.partCount}</p>
    <p><strong>分卷信息:</strong></p>
    ${partsInfo}
  `,
      '查看备份详情',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
      }
    )
  }

  // 处理下载
  const handleDownload = (row: any) => {
    // 构建下载链接
    const downloadUrl = `/home/database/downfile?time=${row.time}&part=${row.part}`
    window.open(downloadUrl, '_blank')
  }

  // 初始化
  onMounted(() => {
    getBackupList()
  })
</script>

<style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .incomplete-warning {
    color: red;
    margin-left: 20px;
  }

  .no-backup {
    padding: 20px 0;
    color: #999;
    text-align: center;
  }

  .restore-progress {
    text-align: center;
  }
</style>
